package org.asiainfo.common.mybatis.listener;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import com.mybatisflex.annotation.InsertListener;
import org.asiainfo.common.core.exception.ServiceException;
import org.asiainfo.common.mybatis.core.domain.BaseEntity;
import org.asiainfo.common.satoken.utils.LoginHelper;

import java.util.Date;

/**
 * 实体类全局插入数据监听器
 *
 * @author dotor-ww
 */
public class EntityInsertListener implements InsertListener {

    /**
     * 插入处理
     *
     * @param entity 参数
     */
    @Override
    public void onInsert(Object entity) {
        try {
            if (ObjectUtil.isNotNull(entity) && (entity instanceof BaseEntity baseEntity)) {
                Long loginUserId = LoginHelper.getUserId();
                Long deptId = LoginHelper.getDeptId();
                Date createTime = ObjectUtil.isNotNull(baseEntity.getCreateTime()) ? baseEntity.getCreateTime() : new Date();
                baseEntity.setCreateDept(deptId);
                baseEntity.setCreateBy(loginUserId);
                baseEntity.setCreateTime(createTime);
            }
        } catch (Exception e) {
            throw new ServiceException("全局插入数据监听器注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
        }
    }
}
